package com.absorbx.security.web.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.absorbx.security.User;
import com.absorbx.security.UserService;

@Controller
public class UserController {
	final Logger logger = Logger.getLogger(UserController.class);

	private static final String LIST_VIEW_KEY = "/user/list";
	private static final String FORM_VIEW_KEY = "/user/form";
	private static final String FORM_MODEL_KEY = "user";
	private static final String SEARCH_MODEL_KEY = "users";
	@Autowired
	protected UserService userService;
	
	 @RequestMapping(value="/user/form.htm")
	    public User create() {
	        return new User();
	    }

	/**
	 * Gets login user's information
	 */
	@RequestMapping(value = "/user/info.htm")
	public ModelAndView info() {
		User user = null;
		Object obj = SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		if (obj instanceof User) {
			user = (User) obj;
		}
		
		return new ModelAndView(FORM_VIEW_KEY, FORM_MODEL_KEY, user);
	}

	@RequestMapping(value = "/user/save.htm")
	public ModelAndView save(User user) {
		logger.debug(user);
		userService.addUser(user);
		return new ModelAndView(FORM_VIEW_KEY, FORM_MODEL_KEY, user);
	}
	@RequestMapping(value="/user/list.htm")
	public ModelAndView list() {
		logger.debug("list usr");
		System.out.println("LIst");
		return new ModelAndView(LIST_VIEW_KEY, SEARCH_MODEL_KEY, userService.getUsers());
	}
//
//	@RequestMapping(value = "/user/suggest.htm")
//	public ModelAndView suggest(@RequestParam("q") String name) {
//		List<User> users = userDao.findUsersByName(name);
//		JsonView jsonView = new JsonView();
//		// exclude property "id"
//		jsonView.exclude("org*");
//
//		return new ModelAndView(jsonView, "model", users);
//	}
}